define(['view', './config', 'model/package'], function(View, Config, Package) {
  return View.extend({

    className: 'shadow',

    templatePath: 'detail.html',

    score: 0,

    events: {
      'click .close': 'hide',
      'click #sendBtn': 'sendComment'
    },

    init: function(pack) {
      this.packageInfo = pack;
    },

    onShow: function() {
      var pack = this.packageInfo;
      if(pack.comments.length > 0) {
        pack.comments = _.sortBy(pack.comments, function(comment) {
          return -comment.comment_time;
        });
        pack.comments = pack.comments.slice(0, 5);
      }
      var html = this.$('#tmpl').html();
      var tmpl = _.template(html);
      this.$el.append(tmpl(this.packageInfo));
      var _this = this;
      this.$('.star li').one('click', function(e) {
        _this.onStarSelected(e);
      });
      $('[pure-content]').css('overflow', 'hidden');
    },

    hide: function() {
      var _this = this;
      this.$('.detail-wrapper').toggleClass('zoomIn zoomOut');
      this.$el.toggleClass('animated fadeOut');
      $('[pure-content]').css('overflow', 'scroll');
      setTimeout(function() {
        View.prototype.hide.call(_this);
      }, 200)
    },

    sendComment: function() {
      var _this = this;
      var text = this.$("#commentText").val().trim();
      if(text.length < 10) return alert("Comment less than 10 chars");

      $.ajax({
        type: 'PUT',
        url: Config.server_url + '/packages/comment/' + this.packageInfo.name + '?access_token=123',
        data: {
          name: this.packageInfo.name,
          comment: text,
          rating: this.score,
          reviewer: 'Anonymous'
        },
        success: function(data) {
          console.log(data)
          _this.$("#commentText").val("");
          _this.trigger('comment-post', data.packages)
          alert('Comment success')
        }
      });
    },

    onStarSelected: function(event) {
      var score = this.score = $(event.currentTarget).data('score');
      var a = $(event.target);
      a.css('width', 30 * score + 'px');
      a.css('left', '0px');
      a.addClass('active');
    } 

  });
})